package com.example.demo.ai.impl;

import com.example.demo.ai.DeepSeekService;
import com.example.demo.ai.config.DeepSeekConfig;
import com.example.demo.ai.model.DeepSeekRequest;
import com.example.demo.ai.model.DeepSeekResponse;
import com.example.demo.ai.model.InterviewAnalysis;
import com.example.demo.ai.model.InterviewQA;
import com.example.demo.ai.model.ResumeAnalysis;
import com.example.demo.ai.model.InterviewQuestionFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.Arrays;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class DeepSeekServiceImpl implements DeepSeekService {

    private static final Logger logger = LoggerFactory.getLogger(DeepSeekServiceImpl.class);
    private static final Pattern QUESTION_PATTERN = Pattern.compile("\\d+\\.\\s*(.*?)(?=\\d+\\.|$)", Pattern.DOTALL);
    private static final Pattern JSON_PATTERN = Pattern.compile("\\{(?:[^{}]|\\{(?:[^{}]|\\{[^{}]*\\})*\\})*\\}",
            Pattern.DOTALL);

    @Autowired
    private DeepSeekConfig deepSeekConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public List<String> generateInterviewQuestions(String resumeText, int questionCount) {
        String prompt = String.format("基于以下简历内容，生成%d个专业相关的面试问题。\n\n" +
                "重要要求：\n" +
                "1. 只返回问题列表，不要添加任何额外说明\n" +
                "2. 每个问题以数字编号开头（如：1. 问题内容）\n" +
                "3. 每个问题单独一行\n" +
                "4. 不要使用Markdown格式\n" +
                "5. 确保问题与简历内容紧密相关\n\n" +
                "简历内容：%s", questionCount, resumeText);

        DeepSeekRequest request = buildRequest(prompt);
        String response = callDeepSeekApi(request);

        return parseQuestions(response, questionCount);
    }

    @Override
    public List<String> generateInterviewQuestions(String resumeText, String jobTitle, String jobDescription,
                                                   String industry, Integer difficulty) {
        String difficultyDesc = getDifficultyDescription(difficulty);

        StringBuilder promptBuilder = new StringBuilder();
        promptBuilder.append(String.format("请根据以下简历内容和目标岗位信息，生成8个适合%s水平的面试问题。\n\n" +
                "重要要求：\n" +
                "1. 只返回问题列表，不要添加任何额外说明\n" +
                "2. 每个问题以数字编号开头（如：1. 问题内容）\n" +
                "3. 每个问题单独一行\n" +
                "4. 不要使用Markdown格式\n" +
                "5. 确保问题紧密结合岗位需求和简历内容\n\n", difficultyDesc));
        promptBuilder.append("目标岗位：").append(jobTitle).append("\n");

        if (industry != null && !industry.isEmpty()) {
            promptBuilder.append("所属行业：").append(industry).append("\n");
        }

        if (jobDescription != null && !jobDescription.isEmpty()) {
            promptBuilder.append("岗位描述：").append(jobDescription).append("\n\n");
        }

        promptBuilder.append("简历内容：").append(resumeText);
        promptBuilder.append("\n\n请确保问题紧密结合岗位需求和简历内容，重点考察应聘者与该岗位的匹配度。");

        DeepSeekRequest request = buildRequest(promptBuilder.toString());
        String response = callDeepSeekApi(request);

        return parseQuestions(response, 8);
    }

    @Override
    public InterviewAnalysis analyzeInterviewAnswers(String resumeText, List<InterviewQA> qaList) {
        StringBuilder promptBuilder = new StringBuilder();
        promptBuilder.append("请根据以下简历内容和面试问答，对面试者的表现进行评分（0-100分）并给出详细的评价和改进建议。\n\n" +
                "请严格按照以下JSON格式返回结果：\n" +
                "{\n" +
                "  \"score\": 数值,\n" +
                "  \"suggestion\": \"字符串\",\n" +
                "  \"strengths\": [\"优势1\", \"优势2\", ...],\n" +
                "  \"areasForImprovement\": [\"改进点1\", \"改进点2\", ...]\n" +
                "}\n\n" +
                "简历内容：\n");
        promptBuilder.append(resumeText);
        promptBuilder.append("\n\n面试问答：\n");

        for (int i = 0; i < qaList.size(); i++) {
            InterviewQA qa = qaList.get(i);
            promptBuilder.append(String.format("问题%d: %s\n", i + 1, qa.getQuestion()));
            promptBuilder.append(String.format("回答%d: %s\n\n", i + 1, qa.getAnswer()));
        }

        DeepSeekRequest request = buildRequest(promptBuilder.toString());
        String response = callDeepSeekApi(request);

        return parseAnalysisResponse(response);
    }

    @Override
    public ResumeAnalysis analyzeResume(String resumeText) {
        String prompt = String.format("请分析以下简历内容，并提供专业的评价和改进建议。\n\n" +
                "请严格按照以下JSON格式返回结果：\n" +
                "{\n" +
                "  \"score\": 数值,\n" +
                "  \"summary\": \"字符串\",\n" +
                "  \"strengths\": \"字符串\",\n" +
                "  \"areasForImprovement\": \"字符串\",\n" +
                "  \"suggestions\": \"字符串\",\n" +
                "  \"formattingTips\": \"字符串\"\n" +
                "}\n\n" +
                "简历内容：\n%s\n\n" +
                "请从以下几个方面进行分析：\n" +
                "1. 整体评分（0-100分）\n" +
                "2. 总体评价\n" +
                "3. 简历中的优势\n" +
                "4. 需要改进的地方\n" +
                "5. 具体的改进建议\n" +
                "6. 格式优化建议", resumeText);

        DeepSeekRequest request = buildRequest(prompt);
        String response = callDeepSeekApi(request);

        return parseResumeAnalysisResponse(response);
    }

    @Override
    public ResumeAnalysis analyzeResume(String resumeText, String jobTitle, String jobDescription) {
        StringBuilder promptBuilder = new StringBuilder();
        promptBuilder.append("请根据以下目标岗位和简历内容，分析应聘者与该岗位的匹配度，并给出简历改进建议。\n\n" +
                "请严格按照以下JSON格式返回结果：" +
                "{\n" +
                "  \"score\": 数值,\n" +
                "  \"summary\": \"字符串\",\n" +
                "  \"matchAnalysis\": \"字符串\",\n" +
                "  \"strengths\": \"字符串\",\n" +
                "  \"areasForImprovement\": \"字符串\",\n" +
                "  \"suggestions\": \"字符串\",\n" +
                "  \"formattingTips\": \"字符串\"\n" +
                "}\n\n");
        promptBuilder.append("目标岗位：").append(jobTitle).append("\n");

        if (jobDescription != null && !jobDescription.isEmpty()) {
            promptBuilder.append("岗位描述：").append(jobDescription).append("\n\n");
        }

        promptBuilder.append("简历内容：").append(resumeText);
        promptBuilder.append("\n\n请从以下几个方面进行分析：\n");
        promptBuilder.append("1. 整体评分（0-100分）\n");
        promptBuilder.append("2. 总体评价\n");
        promptBuilder.append("3. 与目标岗位的匹配度分析\n");
        promptBuilder.append("4. 简历中的优势\n");
        promptBuilder.append("5. 需要改进的地方\n");
        promptBuilder.append("6. 针对目标岗位的具体改进建议\n");
        promptBuilder.append("7. 格式优化建议");

        DeepSeekRequest request = buildRequest(promptBuilder.toString());
        String response = callDeepSeekApi(request);

        return parseResumeAnalysisResponse(response);
    }

    @Override
    public List<InterviewQA> generateExampleAnswers(String resumeText, List<InterviewQA> qaList) {
        logger.info("Generating example answers for {} questions", qaList.size());

        StringBuilder promptBuilder = new StringBuilder();
        promptBuilder.append("基于以下简历内容和面试问题，请为每个问题生成专业、全面的示例答案。\n\n");
        promptBuilder.append("请严格按照以下格式返回结果：\n");
        promptBuilder.append("问题1：[问题文本]\n");
        promptBuilder.append("示例答案1：[专业的示例答案]\n\n");
        promptBuilder.append("问题2：[问题文本]\n");
        promptBuilder.append("示例答案2：[专业的示例答案]\n\n");
        promptBuilder.append("...\n\n");
        promptBuilder.append("简历内容：\n").append(resumeText).append("\n\n");
        promptBuilder.append("面试问题：\n");

        for (int i = 0; i < qaList.size(); i++) {
            promptBuilder.append(String.format("问题%d：%s\n", i + 1, qaList.get(i).getQuestion()));
        }

        promptBuilder.append("\n请确保示例答案专业、全面，适合该岗位的面试场景。");

        DeepSeekRequest request = buildRequest(promptBuilder.toString());
        String response = callDeepSeekApi(request);

        return parseExampleAnswers(response, qaList);
    }

    private List<InterviewQA> parseExampleAnswers(String response, List<InterviewQA> originalQaList) {
        if (response == null || response.trim().isEmpty()) {
            logger.warn("Empty response received for example answers parsing");
            return getDefaultExampleAnswers(originalQaList);
        }

        List<InterviewQA> exampleQas = new ArrayList<>();
        String[] lines = response.split("\n");

        String currentQuestion = null;
        StringBuilder currentAnswer = new StringBuilder();
        boolean isAnswer = false;

        for (String line : lines) {
            line = line.trim();
            if (line.startsWith("问题")) {
                // 如果已经有一个未处理的问题，先保存它
                if (currentQuestion != null) {
                    InterviewQA qa = new InterviewQA();
                    qa.setQuestion(currentQuestion);
                    qa.setAnswer(currentAnswer.toString().trim());
                    exampleQas.add(qa);
                    currentAnswer.setLength(0);
                }

                // 提取问题文本
                int colonIndex = line.indexOf("：");
                if (colonIndex > 0) {
                    currentQuestion = line.substring(colonIndex + 1).trim();
                    isAnswer = false;
                }
            } else if (line.startsWith("示例答案")) {
                // 提取答案文本开始部分
                int colonIndex = line.indexOf("：");
                if (colonIndex > 0) {
                    currentAnswer.append(line.substring(colonIndex + 1).trim());
                    isAnswer = true;
                }
            } else if (isAnswer && !line.isEmpty()) {
                // 继续添加答案内容
                if (currentAnswer.length() > 0) {
                    currentAnswer.append("\n");
                }
                currentAnswer.append(line);
            }
        }

        // 处理最后一个问题和答案
        if (currentQuestion != null) {
            InterviewQA qa = new InterviewQA();
            qa.setQuestion(currentQuestion);
            qa.setAnswer(currentAnswer.toString().trim());
            exampleQas.add(qa);
        }

        // 如果解析结果不完整，使用默认答案补充
        if (exampleQas.isEmpty() || exampleQas.size() < originalQaList.size()) {
            logger.warn("Failed to parse all example answers, using default answers for missing ones");
            return getDefaultExampleAnswers(originalQaList);
        }

        return exampleQas;
    }

    private List<InterviewQA> getDefaultExampleAnswers(List<InterviewQA> originalQaList) {
        List<InterviewQA> defaultExampleQas = new ArrayList<>();

        for (InterviewQA qa : originalQaList) {
            InterviewQA exampleQa = new InterviewQA();
            exampleQa.setQuestion(qa.getQuestion());

            // 根据问题内容提供相应的默认示例答案
            if (qa.getQuestion().contains("介绍自己")) {
                exampleQa.setAnswer(
                        "我是一名经验丰富的软件工程师，拥有多年的相关工作经验。我熟悉Java、Spring框架等技术栈，曾参与多个大型项目的开发。我注重团队合作，善于解决复杂问题，并且持续学习新技术以提升自己的专业能力。我相信我的技能和经验能够为贵公司带来价值。");
            } else if (qa.getQuestion().contains("优势")) {
                exampleQa.setAnswer(
                        "我最大的优势是我的技术能力和解决问题的能力。我能够快速理解业务需求并转化为技术方案，同时在项目中遇到挑战时能够保持冷静并找到有效的解决方案。此外，我还具有良好的团队协作精神，善于与不同背景的同事沟通合作。");
            } else if (qa.getQuestion().contains("改进")) {
                exampleQa.setAnswer(
                        "我认为我在时间管理方面还有提升空间。有时为了追求完美，我会在某些细节上花费过多时间，导致项目进度受到影响。为了改进这一点，我正在学习使用敏捷开发方法和项目管理极狐工具，以更好地平衡质量和效率。");
            } else if (qa.getQuestion().contains("压力")) {
                exampleQa.setAnswer(
                        "面对工作压力，我通常会采取以下策略：首先，我会分解任务，制定详细的计划，确保工作有序进行；其次，我会保持良好的沟通，及时向上级和团队反馈进展；最后，我会通过适当的运动和休息来缓解压力，保持良好的工作状态。");
            } else if (qa.getQuestion().contains("职业规划")) {
                exampleQa.setAnswer(
                        "在未来5年，我希望能够在技术领域不断深耕，成为某一领域的专家。同时，我也希望能够承担更多的责任，带领团队完成更具挑战性的项目。我会持续学习新技术，关注行业发展趋势，不断提升自己的综合能力。");
            } else {
                exampleQa.setAnswer(
                        "这是一个很好的问题。根据我的经验和理解，我认为最佳的做法是根据具体情况进行分析和处理。首先，我会收集相关信息，明确问题的本质；然后，我会考虑多种解决方案，并评估每种方案的优缺点；最后，我会选择最合适的方案并执行，同时不断监控和调整。");
            }

            defaultExampleQas.add(exampleQa);
        }

        return defaultExampleQas;
    }

    private String getDifficultyDescription(Integer difficulty) {
        if (difficulty == null) {
            return "中级";
        }
        switch (difficulty) {
            case 1:
                return "初级";
            case 3:
                return "高级";
            default:
                return "中级";
        }
    }

    private DeepSeekRequest buildRequest(String prompt) {
        DeepSeekRequest request = new DeepSeekRequest();
        request.setModel(deepSeekConfig.getModel());
        request.setMax_tokens(deepSeekConfig.getMaxTokens());
        request.setTemperature(deepSeekConfig.getTemperature());

        List<DeepSeekRequest.Message> messages = new ArrayList<>();
        DeepSeekRequest.Message message = new DeepSeekRequest.Message();
        message.setRole("user");
        message.setContent(prompt);
        messages.add(message);

        request.setMessages(messages);
        return request;
    }

    private String callDeepSeekApi(DeepSeekRequest request) {
        try {
            logger.debug("Calling DeepSeek API with model: {}", deepSeekConfig.getModel());

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + deepSeekConfig.getApiKey());

            HttpEntity<DeepSeekRequest> entity = new HttpEntity<>(request, headers);

            String apiUrl = deepSeekConfig.getBaseUrl() +
                    (deepSeekConfig.getBaseUrl().endsWith("/") ? "" : "/") +
                    "chat/completions";

            logger.debug("API Request: max_tokens={}, temperature={}",
                    request.getMax_tokens(), request.getTemperature());
            logger.debug("API URL: {}", apiUrl);

            long startTime = System.currentTimeMillis();
            ResponseEntity<DeepSeekResponse> responseEntity = restTemplate.postForEntity(
                    apiUrl,
                    entity,
                    DeepSeekResponse.class);
            long endTime = System.currentTimeMillis();

            logger.debug("API call completed in {} ms with status code: {}",
                    (endTime - startTime), responseEntity.getStatusCodeValue());

            if (responseEntity.getStatusCode() != HttpStatus.OK) {
                logger.warn("API returned non-OK status: {}", responseEntity.getStatusCode());
                throw new RuntimeException("API request failed with status: " + responseEntity.getStatusCode());
            }

            DeepSeekResponse response = responseEntity.getBody();
            if (response == null || response.getChoices() == null || response.getChoices().isEmpty()) {
                logger.warn("API returned null or empty response");
                throw new RuntimeException("API returned empty response");
            }

            String content = response.getChoices().get(0).getMessage().getContent();
            logger.debug("API response content: {}", content);
            return content;

        } catch (RestClientException e) {
            logger.error("Error calling DeepSeek API: {}", e.getMessage());
            throw new RuntimeException("Failed to call DeepSeek API", e);
        }
    }

    private List<String> parseQuestions(String response, int expectedCount) {
        if (response == null || response.trim().isEmpty()) {
            logger.warn("Empty response received for questions parsing");
            return getDefaultQuestions(expectedCount);
        }

        List<String> questions = new ArrayList<>();
        logger.debug("API response for questions: {}", response);

        // 方法1: 使用正则表达式解析
        Matcher matcher = QUESTION_PATTERN.matcher(response);
        while (matcher.find() && questions.size() < expectedCount) {
            String question = matcher.group(1).trim();
            if (!question.isEmpty()) {
                questions.add(question);
            }
        }

        // 方法2: 如果正则表达式没有找到，尝试按行解析
        if (questions.isEmpty()) {
            String[] lines = response.split("\\n");
            for (String line : lines) {
                line = line.trim();
                // 跳过空行或太短的行
                if (line.isEmpty() || line.length() < 5) {
                    continue;
                }

                // 匹配数字编号格式：1. 问题内容
                if (line.matches("^\\d+\\.\\s+.+")) {
                    String question = line.replaceFirst("^\\d+\\.\\s*", "");
                    if (!question.trim().isEmpty()) {
                        questions.add(question.trim());
                    }
                }
                // 匹配其他常见格式
                else if (line.matches("^[Qq]\\d*[:：]\\s*.+")) {
                    String question = line.replaceFirst("^[Qq]\\d*[:：]\\s*", "");
                    if (!question.trim().isEmpty()) {
                        questions.add(question.trim());
                    }
                }
                // 匹配带有连字符的格式：- 问题内容
                else if (line.matches("^-\\s+.+")) {
                    String question = line.replaceFirst("^-\\s*", "");
                    if (!question.trim().isEmpty()) {
                        questions.add(question.trim());
                    }
                }
                // 匹配带有星号的格式：* 问题内容
                else if (line.matches("^\\*\\s+.+")) {
                    String question = line.replaceFirst("^\\*\\s*", "");
                    if (!question.trim().isEmpty()) {
                        questions.add(question.trim());
                    }
                }
                // 匹配带有括号编号的格式：(1) 问题内容
                else if (line.matches("^\\(\\d+\\)\\s+.+")) {
                    String question = line.replaceFirst("^\\(\\d+\\)\\s*", "");
                    if (!question.trim().isEmpty()) {
                        questions.add(question.trim());
                    }
                }
                // 匹配纯问题格式（以问号结尾）
                else if (line.endsWith("?") || line.endsWith("？")) {
                    questions.add(line);
                }

                if (questions.size() >= expectedCount) {
                    break;
                }
            }
        }

        // 方法3: 如果前两种方法都失败，尝试简单的分割策略
        if (questions.isEmpty()) {
            logger.warn("Standard parsing methods failed, trying fallback parsing");

            // 清理Markdown格式
            String cleanResponse = response
                    .replace("**", "")
                    .replace("*", "")
                    .replace("`", "")
                    .replace("#", "");

            String[] lines = cleanResponse.split("\\n");
            for (String line : lines) {
                line = line.trim();
                // 跳过空行或太短的行
                if (line.isEmpty() || line.length() < 5) {
                    continue;
                }

                // 添加到问题列表
                questions.add(line);

                if (questions.size() >= expectedCount) {
                    break;
                }
            }
        }

        if (questions.isEmpty()) {
            logger.warn(
                    "No questions found in response after all parsing attempts, using default questions. Response was: {}",
                    response);
            return getDefaultQuestions(expectedCount);
        }

        logger.info("Successfully parsed {} questions from API response", questions.size());
        return questions;
    }

    private List<String> getDefaultQuestions(int count) {
        List<String> defaultQuestions = Arrays.asList(
                "请简单介绍一下你自己。",
                "你为什么对这个职位感兴趣？",
                "你最大的优势是什么？",
                "你认为自己需要改进的地方是什么？",
                "你如何处理工作中的压力？",
                "你过去解决过的最具挑战性的问题是什么？",
                "你如何评价自己的团队合作能力？",
                "你对未来5年的职业规划是什么？");

        return defaultQuestions.subList(0, Math.min(count, defaultQuestions.size()));
    }

    private InterviewAnalysis parseAnalysisResponse(String response) {
        if (response == null || response.trim().isEmpty()) {
            logger.warn("Empty response received for analysis parsing");
            return createDefaultInterviewAnalysis();
        }

        try {
            // 尝试从响应中提取JSON部分
            String jsonContent = extractJsonFromResponse(response);

            // 首先尝试直接解析
            try {
                return objectMapper.readValue(jsonContent, InterviewAnalysis.class);
            } catch (JsonProcessingException e) {
                // 如果直接解析失败，可能是因为strengths和areasForImprovement是字符串而不是列表
                logger.warn("Direct parsing failed, trying to convert string fields to lists: {}", e.getMessage());

                // 先解析为Map
                Map<String, Object> jsonMap = objectMapper.readValue(jsonContent, Map.class);
                InterviewAnalysis analysis = new InterviewAnalysis();

                // 设置基本字段
                analysis.setScore(Double.parseDouble(jsonMap.get("score").toString()));
                analysis.setSuggestion(jsonMap.get("suggestion").toString());

                // 处理strengths字段
                Object strengthsObj = jsonMap.get("strengths");
                List<String> strengthsList = new ArrayList<>();
                if (strengthsObj instanceof String) {
                    // 如果是字符串，按换行符或逗号分割
                    String strengthsStr = (String) strengthsObj;
                    if (strengthsStr.contains("\n")) {
                        strengthsList.addAll(Arrays.asList(strengthsStr.split("\n")));
                    } else if (strengthsStr.contains(",")) {
                        strengthsList.addAll(Arrays.asList(strengthsStr.split(",")));
                    } else {
                        strengthsList.add(strengthsStr);
                    }
                } else if (strengthsObj instanceof List) {
                    // 如果已经是列表，直接添加
                    strengthsList.addAll((List<String>) strengthsObj);
                }
                analysis.setStrengths(strengthsList);

                // 处理areasForImprovement字段
                Object areasObj = jsonMap.get("areasForImprovement");
                List<String> areasList = new ArrayList<>();
                if (areasObj instanceof String) {
                    // 如果是字符串，按极狐换行符或逗号分割
                    String areasStr = (String) areasObj;
                    if (areasStr.contains("\n")) {
                        areasList.addAll(Arrays.asList(areasStr.split("\n")));
                    } else if (areasStr.contains(",")) {
                        areasList.addAll(Arrays.asList(areasStr.split(",")));
                    } else {
                        areasList.add(areasStr);
                    }
                } else if (areasObj instanceof List) {
                    // 如果已经是列表，直接添加
                    areasList.addAll((List<String>) areasObj);
                }
                analysis.setAreasForImprovement(areasList);

                return analysis;
            }
        } catch (Exception e) {
            logger.error("Failed to parse interview analysis response: {}", e.getMessage());
            logger.debug("Response content that failed to parse: {}", response);
            return createDefaultInterviewAnalysis();
        }
    }

    private ResumeAnalysis parseResumeAnalysisResponse(String response) {
        if (response == null || response.trim().isEmpty()) {
            logger.warn("Empty response received for resume analysis parsing");
            return createDefaultResumeAnalysis();
        }

        try {
            // 尝试从响应中提取JSON部分
            String jsonContent = extractJsonFromResponse(response);
            return objectMapper.readValue(jsonContent, ResumeAnalysis.class);
        } catch (JsonProcessingException e) {
            logger.error("Failed to parse resume analysis response: {}", e.getMessage());
            logger.debug("Response content that failed to parse: {}", response);
            return createDefaultResumeAnalysis();
        }
    }

    private String extractJsonFromResponse(String response) {
        // 如果响应本身就是JSON，直接返回
        if (response.trim().startsWith("{") || response.trim().startsWith("[")) {
            return response;
        }

        // 否则尝试从文本中提取JSON
        Matcher matcher = JSON_PATTERN.matcher(response);
        if (matcher.find()) {
            return matcher.group();
        }

        throw new RuntimeException("No valid JSON found in response");
    }

    private InterviewAnalysis createDefaultInterviewAnalysis() {
        InterviewAnalysis analysis = new InterviewAnalysis();
        analysis.setScore(75.0);
        analysis.setSuggestion("无法解析分析结果，请检查API响应格式");

        // 改为List<String>类型
        List<String> defaultStrengths = new ArrayList<>();
        defaultStrengths.add("无法解析优势分析");
        analysis.setStrengths(defaultStrengths);

        List<String> defaultAreasForImprovement = new ArrayList<>();
        defaultAreasForImprovement.add("无法解析改进建议");
        analysis.setAreasForImprovement(defaultAreasForImprovement);

        return analysis;
    }

    private ResumeAnalysis createDefaultResumeAnalysis() {
        ResumeAnalysis analysis = new ResumeAnalysis();
        analysis.setScore(70.0);
        analysis.setSummary("无法解析简历分析结果");
        analysis.setStrengths("无法解析优势分析");
        analysis.setAreasForImprovement("无法解析改进建议");
        analysis.setSuggestions("请检查API响应格式");
        analysis.setFormattingTips("无法提供格式建议");
        return analysis;
    }

    @Override
    public String generateSingleInterviewQuestion(String resumeText, String jobTitle, String jobDescription, String industry, Integer difficulty, List<String> previousQuestions) {
        String difficultyDesc = getDifficultyDescription(difficulty);

        StringBuilder promptBuilder = new StringBuilder();
        promptBuilder.append(String.format("请根据以下简历内容和目标岗位信息，生成1个适合%s水平的面试问题。\n\n", difficultyDesc));
        promptBuilder.append("重要要求：\n");
        promptBuilder.append("1. 只返回问题文本，不要添加任何额外说明\n");
        promptBuilder.append("2. 不要使用Markdown格式\n");
        promptBuilder.append("3. 问题必须紧密结合岗位需求和简历中提到的具体项目经验、技术栈、工作成果\n");
        promptBuilder.append("4. 必须在问题中明确提及简历中具体的项目名称、使用的技术、负责的工作内容或取得的成果\n");
        promptBuilder.append("5. 问题要与之前的问题不同，避免重复\n");
        promptBuilder.append("6. 问题必须以问号结尾\n\n");

        promptBuilder.append("目标岗位：").append(jobTitle).append("\n");

        if (industry != null && !industry.isEmpty()) {
            promptBuilder.append("所属行业：").append(industry).append("\n");
        }

        if (jobDescription != null && !jobDescription.isEmpty()) {
            promptBuilder.append("岗位描述：").append(jobDescription).append("\n\n");
        }

        promptBuilder.append("简历内容：").append(resumeText);
        promptBuilder.append("\n\n");

        // 分析简历中的关键信息，帮助AI更好地理解
        if (resumeText != null && !resumeText.isEmpty()) {
            promptBuilder.append("请重点关注简历中以下类型的信息来生成问题：\n");
            promptBuilder.append("- 项目经验中的具体项目名称、担任角色、负责工作\n");
            promptBuilder.append("- 技术栈中提到的编程语言、框架、工具\n");
            promptBuilder.append("- 工作成果、业绩数据、项目成效\n");
            promptBuilder.append("- 专业技能、认证、培训经历\n\n");
        }

        // 添加之前的问题，让AI避免重复
        if (previousQuestions != null && !previousQuestions.isEmpty()) {
            promptBuilder.append("之前已经问过的问题：\n");
            for (int i = 0; i < previousQuestions.size(); i++) {
                promptBuilder.append(String.format("%d. %s\n", i + 1, previousQuestions.get(i)));
            }
            promptBuilder.append("\n请确保生成的问题与上述问题不同，并覆盖简历中未被充分讨论的项目和技术。");
        }

        DeepSeekRequest request = buildRequest(promptBuilder.toString());
        String response = callDeepSeekApi(request);

        // 解析单个问题
        String question = parseSingleQuestion(response);

        // 如果解析失败，使用默认问题
        if (question == null || question.trim().isEmpty()) {
            logger.warn("Failed to generate single question, using default question");
            return getDefaultQuestions(1).get(0);
        }

        return question;
    }

    private String parseSingleQuestion(String response) {
        if (response == null || response.trim().isEmpty()) {
            return null;
        }

        // 清理响应文本
        String cleanResponse = response.trim()
                .replace("**", "")
                .replace("*", "")
                .replace("`", "")
                .replace("#", "");

        // 移除可能的数字前缀和标点符号
        String[] lines = cleanResponse.split("\\n");
        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty() || line.length() < 5) {
                continue;
            }

            // 处理常见的格式
            if (line.matches("^\\d+\\.\\s+.+")) {
                // 匹配格式：1. 问题内容
                line = line.replaceFirst("^\\d+\\.\\s*", "");
            } else if (line.matches("^[Qq]\\d*[:：]\\s*.+")) {
                // 匹配格式：Q1: 问题内容 或 问题1: 问题内容
                line = line.replaceFirst("^[Qq]\\d*[:：]\\s*", "");
            } else if (line.matches("^-\\s+.+")) {
                // 匹配格式：- 问题内容
                line = line.replaceFirst("^-\\s*", "");
            } else if (line.matches("^\\*\\s+.+")) {
                // 匹配格式：* 问题内容
                line = line.replaceFirst("^\\*\\s*", "");
            } else if (line.matches("^\\(\\d+\\)\\s+.+")) {
                // 匹配格式：(1) 问题内容
                line = line.replaceFirst("^\\(\\d+\\)\\s*", "");
            }

            // 确保问题以问号结尾
            if (line.endsWith("?") || line.endsWith("？")) {
                return line;
            }
        }

        // 如果没有找到以问号结尾的问题，返回第一行有效的文本
        for (String line : lines) {
            line = line.trim();
            if (!line.isEmpty() && line.length() >= 5) {
                // 如果不以问号结尾，添加问号
                if (!line.endsWith("?") && !line.endsWith("？")) {
                    line += "？";
                }
                return line;
            }
        }

        return null;
    }

    @Override
    public List<InterviewQuestionFormat> generateFormattedInterviewQuestions(String resumeText, int questionCount) {
        String prompt = String.format("基于以下简历内容，生成%d个专业相关的面试问题。\n\n" +
                "重要要求：\n" +
                "1. 严格按照JSON格式返回结果，JSON数组中包含%d个对象\n" +
                "2. 不要添加任何JSON以外的说明文字\n" +
                "3. 确保问题与简历内容紧密相关\n\n" +
                "JSON格式要求：\n" +
                "[{\n" +
                "  \"question\": \"问题文本\",\n" +
                "  \"type\": \"问题类型(如：技术问题、行为问题、项目经验问题等)\",\n" +
                "  \"focusPoint\": \"考察重点\",\n" +
                "  \"difficulty\": \"难度级别(如：初级、中级、高级)\",\n" +
                "  \"reason\": \"为什么会问这个问题\"\n" +
                "}]\n\n" +
                "简历内容：%s", questionCount, questionCount, resumeText);

        DeepSeekRequest request = buildRequest(prompt);
        String response = callDeepSeekApi(request);

        return parseFormattedQuestions(response, questionCount);
    }

    @Override
    public List<InterviewQuestionFormat> generateFormattedInterviewQuestions(String resumeText, String jobTitle,
                                                                             String jobDescription, String industry, Integer difficulty) {
        String difficultyDesc = getDifficultyDescription(difficulty);

        StringBuilder promptBuilder = new StringBuilder();
        promptBuilder.append(String.format("请根据以下简历内容和目标岗位信息，生成8个适合%s水平的面试问题。\n\n" +
                "重要要求：\n" +
                "1. 严格按照JSON格式返回结果，JSON数组中包含8个对象\n" +
                "2. 不要添加任何JSON以外的说明文字\n" +
                "3. 确保问题紧密结合岗位需求和简历内容\n\n", difficultyDesc));
        promptBuilder.append("JSON格式要求：\n" +
                "[{\n" +
                "  \"question\": \"问题文本\",\n" +
                "  \"type\": \"问题类型(如：技术问题、行为问题、项目经验问题等)\",\n" +
                "  \"focusPoint\": \"考察重点\",\n" +
                "  \"difficulty\": \"难度级别(如：初级、中级、高级)\",\n" +
                "  \"reason\": \"为什么会问这个问题\"\n" +
                "}]\n\n");
        promptBuilder.append("目标岗位：").append(jobTitle).append("\n");

        if (industry != null && !industry.isEmpty()) {
            promptBuilder.append("所属行业：").append(industry).append("\n");
        }

        if (jobDescription != null && !jobDescription.isEmpty()) {
            promptBuilder.append("岗位描述：").append(jobDescription).append("\n\n");
        }

        promptBuilder.append("简历内容：").append(resumeText);

        DeepSeekRequest request = buildRequest(promptBuilder.toString());
        String response = callDeepSeekApi(request);

        return parseFormattedQuestions(response, 8);
    }

    @Override
    public InterviewQuestionFormat generateSingleFormattedInterviewQuestion(String resumeText, String jobTitle,
                                                                            String jobDescription, String industry, Integer difficulty, List<String> previousQuestions) {
        String difficultyDesc = getDifficultyDescription(difficulty);

        StringBuilder promptBuilder = new StringBuilder();
        promptBuilder.append(String.format("请根据以下简历内容和目标岗位信息，生成1个适合%s水平的面试问题。\n\n", difficultyDesc));
        promptBuilder.append("重要要求：\n");
        promptBuilder.append("1. 严格按照JSON格式返回结果\n");
        promptBuilder.append("2. 不要添加任何JSON以外的说明文字\n");
        promptBuilder.append("3. 确保问题紧密结合岗位需求和简历内容\n");
        promptBuilder.append("4. 问题要与之前的问题不同，避免重复\n\n");

        promptBuilder.append("JSON格式要求：\n" +
                "{\n" +
                "  \"question\": \"问题文本\",\n" +
                "  \"type\": \"问题类型(如：技术问题、行为问题、项目经验问题等)\",\n" +
                "  \"focusPoint\": \"考察重点\",\n" +
                "  \"difficulty\": \"难度级别(如：初级、中级、高级)\",\n" +
                "  \"reason\": \"为什么会问这个问题\"\n" +
                "}\n\n");

        promptBuilder.append("目标岗位：").append(jobTitle).append("\n");

        if (industry != null && !industry.isEmpty()) {
            promptBuilder.append("所属行业：").append(industry).append("\n");
        }

        if (jobDescription != null && !jobDescription.isEmpty()) {
            promptBuilder.append("岗位描述：").append(jobDescription).append("\n\n");
        }

        promptBuilder.append("简历内容：").append(resumeText);
        promptBuilder.append("\n\n");

        // 添加之前的问题，让AI避免重复
        if (previousQuestions != null && !previousQuestions.isEmpty()) {
            promptBuilder.append("之前已经问过的问题：\n");
            for (int i = 0; i < previousQuestions.size(); i++) {
                promptBuilder.append(String.format("%d. %s\n", i + 1, previousQuestions.get(i)));
            }
            promptBuilder.append("\n请确保生成的问题与上述问题不同。");
        }

        DeepSeekRequest request = buildRequest(promptBuilder.toString());
        String response = callDeepSeekApi(request);

        return parseSingleFormattedQuestion(response);
    }

    private List<InterviewQuestionFormat> parseFormattedQuestions(String response, int expectedCount) {
        if (response == null || response.trim().isEmpty()) {
            logger.warn("Empty response received for formatted questions parsing");
            return getDefaultFormattedQuestions(expectedCount);
        }

        try {
            // 尝试从响应中提取JSON部分
            String jsonContent = extractJsonFromResponse(response);

            // 解析JSON数组
            InterviewQuestionFormat[] questionsArray = objectMapper.readValue(jsonContent, InterviewQuestionFormat[].class);
            List<InterviewQuestionFormat> questionsList = Arrays.asList(questionsArray);

            // 确保返回足够数量的问题
            if (questionsList.size() < expectedCount) {
                List<InterviewQuestionFormat> result = new ArrayList<>(questionsList);
                // 添加默认问题以达到预期数量
                List<InterviewQuestionFormat> defaultQuestions = getDefaultFormattedQuestions(expectedCount - questionsList.size());
                result.addAll(defaultQuestions);
                return result;
            }

            return questionsList.subList(0, expectedCount);
        } catch (Exception e) {
            logger.error("Failed to parse formatted questions response: {}", e.getMessage());
            logger.debug("Response content that failed to parse: {}", response);
            return getDefaultFormattedQuestions(expectedCount);
        }
    }

    private InterviewQuestionFormat parseSingleFormattedQuestion(String response) {
        if (response == null || response.trim().isEmpty()) {
            logger.warn("Empty response received for single formatted question parsing");
            return getDefaultFormattedQuestions(1).get(0);
        }

        try {
            // 尝试从响应中提取JSON部分
            String jsonContent = extractJsonFromResponse(response);
            return objectMapper.readValue(jsonContent, InterviewQuestionFormat.class);
        } catch (Exception e) {
            logger.error("Failed to parse single formatted question response: {}", e.getMessage());
            logger.debug("Response content that failed to parse: {}", response);
            return getDefaultFormattedQuestions(1).get(0);
        }
    }

    private List<InterviewQuestionFormat> getDefaultFormattedQuestions(int count) {
        List<InterviewQuestionFormat> defaultQuestions = new ArrayList<>();

        // 默认问题库
        Map<String, Map<String, String>> questionTemplates = new LinkedHashMap<>();
        // 使用HashMap替代Map.of()以兼容Java 8
        Map<String, String> template1 = new HashMap<>();
        template1.put("type", "行为问题");
        template1.put("focusPoint", "沟通能力、自我认知");
        template1.put("difficulty", "初级");
        template1.put("reason", "了解应聘者的基本情况和沟通表达能力");
        questionTemplates.put("请简单介绍一下你自己。", template1);

        Map<String, String> template2 = new HashMap<>();
        template2.put("type", "动机问题");
        template2.put("focusPoint", "求职动机、岗位认知");
        template2.put("difficulty", "初级");
        template2.put("reason", "了解应聘者的求职动机和对岗位的理解");
        questionTemplates.put("你为什么对这个职位感兴趣？", template2);

        Map<String, String> template3 = new HashMap<>();
        template3.put("type", "行为问题");
        template3.put("focusPoint", "自我评估、核心竞争力");
        template3.put("difficulty", "中级");
        template3.put("reason", "了解应聘者的核心竞争力和自我认知");
        questionTemplates.put("你最大的优势是什么？", template3);

        Map<String, String> template4 = new HashMap<>();
        template4.put("type", "行为问题");
        template4.put("focusPoint", "自我反思、成长潜力");
        template4.put("difficulty", "中级");
        template4.put("reason", "了解应聘者的自我反思能力和成长潜力");
        questionTemplates.put("你认为自己需要改进的地方是什么？", template4);

        Map<String, String> template5 = new HashMap<>();
        template5.put("type", "行为问题");
        template5.put("focusPoint", "压力管理、应变能力");
        template5.put("difficulty", "中级");
        template5.put("reason", "了解应聘者的压力管理能力和应变能力");
        questionTemplates.put("你如何处理工作中的压力？", template5);

        Map<String, String> template6 = new HashMap<>();
        template6.put("type", "项目经验问题");
        template6.put("focusPoint", "问题解决能力、技术深度");
        template6.put("difficulty", "高级");
        template6.put("reason", "了解应聘者的问题解决能力和技术深度");
        questionTemplates.put("你过去解决过的最具挑战性的问题是什么？", template6);

        Map<String, String> template7 = new HashMap<>();
        template7.put("type", "行为问题");
        template7.put("focusPoint", "团队协作、人际关系");
        template7.put("difficulty", "中级");
        template7.put("reason", "了解应聘者的团队协作能力和人际交往能力");
        questionTemplates.put("你如何评价自己的团队合作能力？", template7);

        Map<String, String> template8 = new HashMap<>();
        template8.put("type", "动机问题");
        template8.put("focusPoint", "职业规划、发展潜力");
        template8.put("difficulty", "中级");
        template8.put("reason", "了解应聘者的职业规划和与公司发展的匹配度");
        questionTemplates.put("你对未来5年的职业规划是什么？", template8);

        // 生成指定数量的默认问题
        int i = 0;
        for (Map.Entry<String, Map<String, String>> entry : questionTemplates.entrySet()) {
            if (i >= count) break;

            InterviewQuestionFormat question = new InterviewQuestionFormat();
            question.setQuestion(entry.getKey());
            question.setType(entry.getValue().get("type"));
            question.setFocusPoint(entry.getValue().get("focusPoint"));
            question.setDifficulty(entry.getValue().get("difficulty"));
            question.setReason(entry.getValue().get("reason"));

            defaultQuestions.add(question);
            i++;
        }

        // 如果需要更多问题，重复添加
        while (defaultQuestions.size() < count) {
            for (InterviewQuestionFormat question : new ArrayList<>(defaultQuestions)) {
                if (defaultQuestions.size() >= count) break;
                // 创建一个新的问题对象，避免引用相同对象
                InterviewQuestionFormat clonedQuestion = new InterviewQuestionFormat();
                clonedQuestion.setQuestion(question.getQuestion());
                clonedQuestion.setType(question.getType());
                clonedQuestion.setFocusPoint(question.getFocusPoint());
                clonedQuestion.setDifficulty(question.getDifficulty());
                clonedQuestion.setReason(question.getReason());
                defaultQuestions.add(clonedQuestion);
            }
        }

        return defaultQuestions;
    }

    @Override
    public String generateSingleInterviewQuestionWithAnswers(String resumeText, String jobTitle, String jobDescription, String industry, Integer difficulty, List<InterviewQA> qaList) {
        logger.info("Generating single interview question with previous answers");

        StringBuilder promptBuilder = new StringBuilder();
        promptBuilder.append(String.format("请根据以下简历内容、目标岗位信息和之前的问答，生成1个适合%s水平的面试问题。\n\n",
                difficulty != null ? getDifficultyDescription(difficulty) : "中级"));
        promptBuilder.append("重要要求：\n");
        promptBuilder.append("1. 只返回问题文本，不要添加任何额外说明\n");
        promptBuilder.append("2. 不要使用Markdown格式\n");
        promptBuilder.append("3. 问题必须紧密结合岗位需求、简历中提到的具体项目经验、技术栈、工作成果和之前的问答\n");
        promptBuilder.append("4. 必须在问题中明确提及简历中具体的项目名称、使用的技术、负责的工作内容或取得的成果\n");
        promptBuilder.append("5. 问题要具有连贯性，基于面试者之前的回答进行追问或延伸，同时与简历内容紧密关联\n");
        promptBuilder.append("6. 问题必须以问号结尾\n\n");

        promptBuilder.append("目标岗位：").append(jobTitle).append("\n");

        if (industry != null && !industry.isEmpty()) {
            promptBuilder.append("所属行业：").append(industry).append("\n");
        }

        if (jobDescription != null && !jobDescription.isEmpty()) {
            promptBuilder.append("岗位描述：").append(jobDescription).append("\n\n");
        }

        promptBuilder.append("简历内容：").append(resumeText);
        promptBuilder.append("\n\n");

        // 分析简历中的关键信息，帮助AI更好地理解
        if (resumeText != null && !resumeText.isEmpty()) {
            promptBuilder.append("请重点关注简历中以下类型的信息来生成问题：\n");
            promptBuilder.append("- 项目经验中的具体项目名称、担任角色、负责工作\n");
            promptBuilder.append("- 技术栈中提到的编程语言、框架、工具\n");
            promptBuilder.append("- 工作成果、业绩数据、项目成效\n");
            promptBuilder.append("- 专业技能、认证、培训经历\n\n");
        }

        // 添加之前的问答，让AI基于回答生成新问题
        if (qaList != null && !qaList.isEmpty()) {
            promptBuilder.append("之前的问答：\n");
            for (int i = 0; i < qaList.size(); i++) {
                InterviewQA qa = qaList.get(i);
                promptBuilder.append(String.format("问题%d: %s\n", i + 1, qa.getQuestion()));
                promptBuilder.append(String.format("回答%d: %s\n\n", i + 1, qa.getAnswer()));
            }
            promptBuilder.append("请基于上述问答，并结合简历中的具体项目和技术细节，生成一个连贯性强且针对性强的新问题。");
        }

        DeepSeekRequest request = buildRequest(promptBuilder.toString());
        String response = callDeepSeekApi(request);

        // 解析单个问题
        String question = parseSingleQuestion(response);

        // 如果解析失败，使用默认问题
        if (question == null || question.trim().isEmpty()) {
            logger.warn("Failed to generate single question with answers, using default question");
            return getDefaultQuestions(1).get(0);
        }

        return question;
    }
}